<template>

  <div>

    <!--顶部面包屑区域    -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in history" :key="item.id">
        {{item.name}}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 操作区域 -->
    <div style="margin: 0 0 20px 0;">
      <el-button type="primary" size="medium"
                 @click="$router.push('/sys-admin/product/category/add-new')">
        添加类别
      </el-button>
    </div>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column label="图标" width="80" align="center">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.icon"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="240" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="keywords" label="关键词" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column label="是否启用" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="显示在导航栏" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleDisplay(scope.row)"
              v-model="scope.row.isDisplay"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="子级类别" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="small" :disabled="scope.row.isParent == 0"
                     @click="showSubCategoryList(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-edit" circle type="primary"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="small" icon="el-icon-delete" circle type="danger"
                     :disabled="scope.row.isParent == 1"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px auto;text-align: right;">
      <el-button size="small" v-if="currentParentId != 0"
                 @click="goBack()">返回
      </el-button>
    </div>

    <el-dialog title="编辑类别" :visible.sync="dialogFormVisible"
               @closed="resetForm('editForm')">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="130px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="editForm.icon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>


<script>
export default {
  data() {
    return {
      tableData: [],
      history: [],
      currentParentId: 0,
      dialogFormVisible: false,
      editForm: {
        id: '',
        name: '',
        keywords: '',
        sort: '',
        icon: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入类别名称', trigger: 'blur'},
          {min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
        ],
        keywords: [
          {required: true, message: '请输入关键词', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99', trigger: 'blur'}
        ],
        icon: [
          {required: true, message: '请输入图标', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {

    // 切换启用状态
    toggleEnable(category){
      let enableText = ['禁用', '启用'];
      let urlMethod = ['disable','enable'];
      let enable = category.enable;
      let url = "http://localhost:9480/categories/" + category.id + "/" + urlMethod[enable];

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$message.success('将【' + category.name + '】的启用状态修改为【' + enableText[enable] + '】成功！');
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 切换显示状态
    toggleDisplay(category){
      let enableText = ['隐藏', '显示'];
      let urlMethod = ['hidden', 'display'];
      let isDisplay = category.isDisplay;
      console.log("isDisplay", isDisplay);
      let url = "http://localhost:9480/categories/" + category.id + "/" + urlMethod[isDisplay];

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$message.success('将【' + category.name + '】的显示状态修改为【' + enableText[isDisplay] + '】成功！');
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //打开编辑对话框
    openEditDialog(category){
      let url = "http://localhost:9480/categories/"+ category.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        }
      });
    },
    //提交编辑表单
    submitEditForm(){
      let url = "http://localhost:9480/categories/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify({
            title: '提示',
            message: '编辑类别成功！'
          });
          this.dialogFormVisible = false;
          this.loadCategoryList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadCategoryList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },


    //打开删除对话框
    openDeleteConfirm(category) {
      this.$confirm('此操作将永久删除【 ' + category.id + '-' + category.name + ' 】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(category);
      }).catch(() => {
      });
    },
    //删除操作
    handleDelete(category) {
      let url = "http://localhost:9480/categories/" + category.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        } else if (jsonResult.state == 40900 || jsonResult.state == 50100 || jsonResult.state == 50200) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });

    },
    //返回
    goBack() {
      let oneCategory = this.history[this.history.length - 1];
      this.history.pop();
      this.currentParentId = oneCategory.parentId;
      this.loadCategoryList();
    },
    //查看子级详情
    showSubCategoryList(category) {
      this.history[category.depth - 1] = category;
      this.currentParentId = category.id;
      this.loadCategoryList();
    },
    // 加载相册列表
    loadCategoryList() {

      let url = 'http://localhost:9480/categories/list-by-parent?queryType=all&parentId=' + this.currentParentId;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');


      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.tableData = jsonResult.data.list;
              this.total = jsonResult.data.total;
              this.pageSize = jsonResult.data.pageSize;
              this.currentPage = jsonResult.data.currentPage;

            } else {

              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {

                }
              });

            }
          }
      )


    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadCategoryList();
  }
}
</script>


